const spawn = require("child_process");
const { Menu } = require('electron');

const program = require("../common/program");

const db = require('../database');

const { getShellMenuController } = require("./menuController");

function shellTestController(sender, res) {
  let result = false;
  let flag = false;
  let child = spawn.exec(res.shell_content, (error, stdout, stderr)=>{
    flag = true;
    if(!result) {
      if(error) {
        sender.reply("shell-test-reply", {
          message: "error",
          result: stderr
        });
      } else {
        let content;
        if(res.result_reg) {
          content = stdout.match(RegExp(res.result_reg));
          content = content?content[0]:"";
        } else {
          content = stdout;
        }
        sender.reply("shell-test-reply", {
          message: "success",
          result: content
        });
      }
    }
  });
  setTimeout(() => {
    result = child.kill("SIGINT");
    if(result) {
      sender.reply("shell-test-reply", {
        message: "warning",
        result: "你的程序执行时间超过10s，请谨慎提交！"
      });
    } else {
      if(!flag) {
        sender.reply("shell-test-reply", {
          message: "error",
          result: "你的程序执行没有响应，且无法杀死，怀疑是后台进程。\n关闭应用会结束后台程序，如果需要提前结束请亲自清理！"
        });
      }
    }
  }, 10000);
}
function shellPutController(_, res) {
  let temp = db.get('userDefineShell').find({label: res.label});
  if(temp.value()) {
    temp.assign(res);
    program.appTrayMenuTemplate[0].submenu.forEach((item, ind) => {
      if(item.label == res.label)
      program.appTrayMenuTemplate[0].submenu[ind] = {
        label: res.label,
        click: getShellMenuController(res),
        type: "radio"
      };
    })
  } else {
    db.get('userDefineShell').push(res).write();
    program.appTrayMenuTemplate[0].submenu.splice(1, 0, {
      label: res.label,
      click: getShellMenuController(res),
      type: "radio"
    });
  }
  contextMenu = Menu.buildFromTemplate(program.appTrayMenuTemplate);
	program.appTray.setContextMenu(contextMenu);
}
function shellDeleteController(sender, res) {
  db.get("userDefineShell").remove({"label": res}).write();
  sender.reply("shell-delete-reply", db.get('userDefineShell').value());
}
function shellDataGetController(sender) {
  sender.reply("shell-data-get-reply", db.get('userDefineShell').value());
}

function shellStatusgetController(sender) {
  sender.reply("change-active-shell", program.appTrayActiveMenu)
}

module.exports = {
  shellTestController,
  shellPutController,
  shellDeleteController,
  shellDataGetController,
  shellStatusgetController
}